package com.matrix.framework.core.component;

import com.matrix.framework.core.common.result.Result;
import com.matrix.framework.core.i18n.I18n;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT密钥管理控制器
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2024/12/19 11:00
 * @Since 1.2
 */
@RestController
@RequestMapping("/admin/jwt")
public class JwtKeyController {

    private final JwtKeyManager keyManager;

    public JwtKeyController(JwtKeyManager keyManager) {
        this.keyManager = keyManager;
    }

    /**
     * 手动触发密钥轮换
     */
    @PostMapping("/rotate")
    public Result<Map<String, Object>> rotateKey() {
        try {
            String oldKeyId = keyManager.getCurrentKeyId();
            keyManager.rotateKey();
            String newKeyId = keyManager.getCurrentKeyId();
            
            Map<String, Object> result = new HashMap<>();
            result.put("oldKeyId", oldKeyId);
            result.put("newKeyId", newKeyId);
            result.put("message", I18n.getMessage("jwt.key.rotation.success"));
            
            return Result.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", I18n.getMessage("jwt.key.rotation.failed") + ": " + e.getMessage());
            return Result.fail(errorResult);
        }
    }

    /**
     * 获取当前密钥信息
     */
    @GetMapping("/info")
    public Result<Map<String, Object>> getKeyInfo() {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("currentKeyId", keyManager.getCurrentKeyId());
            result.put("validKeysCount", keyManager.getValidKeys().size());
            
            return Result.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", I18n.getMessage("jwt.key.info.failed") + ": " + e.getMessage());
            return Result.fail(errorResult);
        }
    }

    /**
     * 获取所有有效密钥信息（仅管理员可见）
     */
    @GetMapping("/keys")
    public Result<Map<String, Object>> getAllKeys() {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("validKeys", keyManager.getValidKeys().keySet());
            result.put("currentKeyId", keyManager.getCurrentKeyId());
            
            return Result.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", I18n.getMessage("jwt.key.list.failed") + ": " + e.getMessage());
            return Result.fail(errorResult);
        }
    }
} 